<template>
  <div ref="box" class="layout" @mouseup="handleMouseup">
    <div ref="treeRef" class="tree-container">
      <el-button size="mini" style="margin: 5px 5px 0;" @click="getData(treeData[0].label)">刷新</el-button>
      <el-dropdown trigger="click" :hide-on-click="true" class="btnleft">
        <el-button size="mini" type="primary">
          {{ $t('market.treehandle') }}<!--节点操作-->
          <i class="el-icon-arrow-down el-icon--right" />
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item :disabled="bomType===1" @click.native="addTree">
            {{ $t('menu.createBom') }}<!--新增BOM-->
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <br>
      <el-input v-model.trim="filterText" placeholder="输入关键字进行过滤" size="mini" style="max-width: 400px;margin: 5px;" />
      <div class="treeBom">
        <!--左边树-->
        <el-tree
          ref="tree"
          :data="treeData"
          node-key="id"
          :expand-on-click-node="false"
          :default-expanded-keys="defauExpended"
          highlight-current
          class="tree"
          :indent="0"
          :filter-node-method="filterNode"
          @node-click="handleNode"
        >
          <span slot-scope="{ node, data }">
            <div class="title-tree">
              {{ data.label }}
              <i
                v-show="data.id === 1"
                :class="data.icon"
                @click.stop="isMateriaHeader=true"
              />
              <el-tooltip
                class="item"
                effect="dark"
                :open-delay="800"
                :content="data.fdescripTion"
                placement="top-start"
              >
                <div class="descripTion">
                  {{ data.fdescripTion }}
                </div>
              </el-tooltip>
            </div>
          </span>
        </el-tree>
      </div>
    </div>
    <div ref="resize" class="resize" @mousedown="handleResize" />
    <!--右侧组件信息-->
    <div ref="mid" class="operation">
      <div v-if="bomType === 1" class="newly-build">
        <jc-detail-bom
          :fnumbers="FNUMBER"
          @copy="copyBom"
          @pushMater="addMateriel"
          @reloadBom="getData(treeData[0].label)"
          @delBom="getData(treeData[0].label, 1)"
        />
      </div>
      <div v-if="bomType === 2" class="newly-build">
        <jc-detail-materiel :fnumber="fnumber2" @showMateriel="copyMater" />
      </div>
      <div v-if="bomType === 3" class="newly-build">
        <jc-create-materiel :fnumber="fnumber3" @addMateriel="addMateriel" />
      </div>
      <div v-if="bomType === 4" class="newly-build">
        <jc-copy-bom
          :f-n-u-m-b-e-r="fnumber4"
          :add-bom="addBom1"
          @addNode="getData"
          @replaceNode="openTree"
          @jumpDetail="addMateriel"
        />
      </div>
    </div>
    <!--  表头父项物料弹窗  -->
    <materDia v-if="isMateriaHeader" @mater="materHeader" />
  </div>
</template>

<script>
import jcDetailBom from '../detailTree/detailBom'
import jcDetailMateriel from '@/views/basic/material/detailMateriel'
import { queryBomTreeDetail } from '@/api/engineering/deitalBom'
export default {
  name: 'DetailTree',
  components: {
    jcCopyBom: () => import('../copyBom'),
    jcCreateMateriel: () => import('@/views/basic/createMateriel2'),
    materDia: () => import('@/views/engineering/detailTree/materDia'),
    jcDetailBom, // bom详情
    jcDetailMateriel // 物料详情
  },
  data() {
    const treeData = [
      {
        label: '', // 名称:id
        id: 1,
        icon: 'el-icon-search',
        children: []
      }
    ]
    return {
      addBom1: {},
      fnumber2: '',
      fnumber3: '',
      fnumber4: '',
      filterText: '',
      showData: {}, // 点击节点，保存节点数据，刷新后使用
      defauExpended: [1],
      treeData: JSON.parse(JSON.stringify(treeData)),
      bomType: '', // 0 为bom， 1为物料
      FNUMBER: '', // 传给详情bom的物料编码
      fnumber: '', // 传给详情物料的物料编码
      isMateriaHeader: false
    }
  },
  watch: {
    // 过滤
    filterText(val) {
      this.$refs.tree.filter(val)
    }
    // treeData: {
    //   handler(val) {
    //     // 选中第一个节点
    //     this.handleNode(val[0])
    //   },
    //   immediate: true,
    //   deep: true
    // }
  },
  created() {
    if (this.$route.params.id) {
      this.getData()
    }
  },
  methods: {
    // 新增物料跳转详情
    addMateriel(ev) {
      this.bomType = 2
      setTimeout(() => {
        this.fnumber2 = ev
      }, 100)
    },
    // 复制物料
    copyMater(ev) {
      this.bomType = 3
      setTimeout(() => {
        this.fnumber3 = ev
      }, 100)
    },
    // 复制BOM
    copyBom(ev) {
      this.bomType = 4
      setTimeout(() => {
        this.fnumber4 = ev
        this.addBom1 = ''
      }, 100)
    },
    // 复制BOM成功，新打开一个树形bom
    openTree(ev) {
      this.$router.push({ path: `/treeBom/${ev}` })
    },
    // 父项物料
    materHeader(item) {
      if (item.FMATERIALID) {
        this.treeData[0].label = item.FNUMBER
        this.getData(item.FNUMBER)
        this.FNUMBER = item.FNUMBER
        this.FMATERIALID = item.FMATERIALID
        this.addBom = { FMATERIALID: item.FMATERIALID, FNUMBER: item.FNUMBER }
      }
      this.isMateriaHeader = false
    },
    // 获取tree数据
    async getData(ev, en) {
      const fnumber = this.treeData[0].label || ev || this.$route.params.id
      if (fnumber === ':id' || !fnumber) return
      const { data: res, code, message } = await queryBomTreeDetail({ fnumber })
      if (code !== 0) {
        this.$confirm(message, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
        return
      }
      // 递归修改后端返回数据名称
      this.treeData = res.allChildList || [{
        label: this.FNUMBER, // 名称
        fmaterialId: this.FMATERIALID, // 名称
        icon: 'el-icon-search',
        id: 1,
        children: []
      }]
      if (en === 1) {
        this.showData.bomType = 2
      } else if (en === 2) {
        this.showData.bomType = 1
      }
      // if (!this.showData.label) {
      //   this.showData = { ...this.treeData[0] }
      // }
      this.handleNode(this.showData || this.treeData[0])
    },
    // 选中节点
    async handleNode(data, node) {
      if (data.fmaterialId) {
        this.addBom = { FMATERIALID: data.fmaterialId, FNUMBER: data.label }
      }
      this.defauExpended[1] = data.id
      this.showData = data
      if (data.bomType === 1) {
        this.bomType = 1
        this.FNUMBER = data.label
      } else {
        this.bomType = 2
        this.fnumber2 = data.label
      }
    },
    // 添加节点
    addTree() {
      this.bomType = 4
      setTimeout(() => {
        this.fnumber4 = ''
        this.addBom1 = this.addBom
      }, 100)
    },
    // 删除节点
    delTree() {
      if (!this.node) {
        return
      }
      const parent = this.node.parent
      if (!parent) {
        this.$message.warning('请点击节点再删除！')
        return
      }
      const children = parent.data.children || parent.data
      const index = children.findIndex(
        d => d.fmaterialId === this.treeData.fmaterialId
      )
      if (this.node.id === 1 || this.node.level === 1) {
        this.$message.warning('不能删除首条数据')
        return
      }
      if (this.isEdit === 0) {
        this.$message.warning(
          '无法删除节点，请检查当前节点或父节点是否审核通过或审核中'
        )
        return
      }
      children.splice(index, 1)
    },
    // 鼠标按下
    handleResize(e) {
      const { resize, box, treeRef: left, mid } = this.$refs
      resize.style.background = '#818181'
      const startX = e.clientX
      resize.left = resize.offsetLeft
      document.onmousemove = function(e) {
        const endX = e.clientX
        let moveLen = resize.left + (endX - startX)
        const maxT = box.clientWidth - resize.offsetWidth
        if (moveLen < 32) {
          moveLen = 32
        }
        if (moveLen > maxT - 150) {
          moveLen = maxT - 150
        }
        resize.style.left = moveLen
        left.style.width = moveLen + 'px'
        mid.style.width = box.clientWidth - moveLen - 10 + 'px'
      }
    },
    // 鼠标松开
    handleMouseup() {
      const { resize } = this.$refs
      resize.style.background = '#d6d6d6'
      document.onmousemove = null
      document.onmouseup = null
      resize.releaseCapture && resize.releaseCapture()
    },
    // 过滤
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    }
  }
}
</script>

<style scoped lang="scss">
@import 'src/styles/tree/index';
.tree-container {
  background-color: #fff;
}
.treeBom {
  height: 80vh;
  overflow-y: auto;
  overflow-x: hidden;
}
.operation {
  padding: 0;
}
</style>
